/**
 * Created by rockyren on 14/12/10.
 */

define(['commonJS/module'],function(commonModule){
  /**
   * 全局消息服务
   * 消息类型分为: success,info,warning,error
   * 每个返回的公共函数都有一个options对象参数,其属性的含义为
   * title: 消息标题
   * msg: 消息信息
   * clickAction: 消息点击动作,该属性有两种类型:
   *      string: 跳转的状态字符串
   *      function: 点击调用的函数
   * 其他属性值可与toasty的属性值相同
   */
  commonModule.factory('GlobalNotificationService', ['toasty', '$state', function(toasty, $state){
    /**
     * 默认的参数对象
     * @type {{title: string, msg: string, timeout: number, showClose: boolean, clickToClose: boolean, myData: string, onClick: Function}}
     */
    var defaultOptions = {
      title: '',
      msg: '',
      timeout: 5000,
      showClose: true,
      clickToClose: false,
      myData: 'Testing 1 2 3',
      onClick: function(){
      }


    };


    var messagesTypes = ['success', 'warning', 'info', 'error'];

    return {
      init: function(scope){

        messagesTypes.forEach(function(currentType){
           //实现监听
           scope.$on('message:' + currentType,function(e, userOptions){
               var options;

               if( userOptions ){
                   options = getExtendObj(userOptions);
               }
               else{
                   options = defaultOptions;
               }

               toasty.pop[currentType](options);
           });
        });
      }
    };

    /**
     * 将一个对象的属性扩展到另一个对象
     * @param receivingObj
     * @param givingObj
     * @returns {*}
     */
    function extend(receivingObj, givingObj) {
      for(prop in givingObj) {
        //如果没有这个属性,则添加到receivingObj
        if(!receivingObj.hasOwnProperty(prop)) {
          receivingObj[prop] = givingObj[prop];
        }
      }
      return receivingObj;
    }

    /**
     * 获得扩展后的对象
     * @param options
     * @returns {*}
     */
    function getExtendObj(options){
      var extendObj;

      extendObj = extend(options,defaultOptions);

      //根据clickAction的类型,设置不同的点击事件
      if(extendObj.hasOwnProperty('clickAction')){

        //如果clickAction是string,则点击时状态跳转
        if(typeof extendObj.clickAction == 'string') {

          extendObj.onClick = function() {
            $state.go(extendObj.clickAction);

          }
        }
        //如果clickAction是function,则点击时调用该函数
        else if(typeof extendObj.clickAction == 'function'){
          extendObj.onClick = function() {
              extendObj.clickAction();
          }
        }

      }


      return extendObj;


    }
  }]);

});